﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;

namespace Utils
{
    public static class XMLUtil
    {
        /// <summary>
        /// Changes the XML encoding.
        /// </summary>
        /// <param name="xmlDoc">The XmlDocument.</param>
        /// <param name="newEncoding">The new encoding.</param>
        /// <returns></returns>
        public static XmlDocument ChangeXmlEncoding(XmlDocument xmlDoc, string newEncoding)
        {
            try
            {
                if (xmlDoc != null)
                {
                    if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        XmlDeclaration xmlDeclaration = (XmlDeclaration)xmlDoc.FirstChild;
                        xmlDeclaration.Encoding = newEncoding;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return xmlDoc;
        }


        /// <summary>
        /// Gets a character by the hex code
        /// </summary>
        /// <param name="hexcode"></param>
        /// <returns></returns>
        public static char GetCharByHexCode(string hexcode)
        {
            Char schar = ' ';
            try
            {
                byte newByte = byte.Parse(hexcode, System.Globalization.NumberStyles.HexNumber);
                int i = Convert.ToInt32(newByte.ToString());
                schar = Convert.ToChar(i);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return schar;
        }

        /// <summary>
        /// Reads the content of a file.
        /// </summary>
        /// <param name="path"></param>
        /// <returns>The content of a file in string format</returns>
        public static string ReadFromFile(string path)
        {
            string fileContents = string.Empty;
            try
            {
                using (StreamReader textFile = new StreamReader(path))
                {
                    fileContents = textFile.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return fileContents;
        }
    }
}